package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.DWaybillStatusEnum;
import cn.huiyunche.base.service.enums.DWaybillStatusTypeEnum;
import cn.huiyunche.base.service.interfaces.DWaybillStatusHistoryService;
import cn.huiyunche.base.service.interfaces.TmsOrderService;
import cn.huiyunche.base.service.interfaces.TmsOrderStatusHistoryService;
import cn.huiyunche.base.service.interfaces.TmsQueueService;
import cn.huiyunche.base.service.mappers.DWaybillMapper;
import cn.huiyunche.base.service.mappers.TmsOrderMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.TmsQueueOrderVo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @FileName: cn.huiyunche.base.service.interfaces.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2016/11/2 上午9:57
 */
@Service
public class TmsOrderServiceImpl implements TmsOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TmsOrderServiceImpl.class);

    @Autowired
    private TmsOrderMapper tmsOrderMapper;

    @Autowired
    private TmsOrderStatusHistoryService tmsOrderStatusHistoryService = null;

    @Autowired
    private DWaybillStatusHistoryService dWaybillStatusHistoryService = null;

    @Autowired
    private TmsQueueService tmsQueueService = null;

    @Autowired
    private DWaybillMapper dWaybillMapper = null;

    /**
     * 检查运单是否取消状态
     *
     * @param ilineid
     */
    private void checkDwaybillIsCancel(String ilineid) throws Exception {
        DWaybillExample dwe = new DWaybillExample();
        dwe.createCriteria().andOrderLineIdEqualTo(ilineid).andUserIdEqualTo(-1L).andWaybillStatusEqualTo(DWaybillStatusEnum.FAILURE.getValue());
        List<DWaybill> list = this.dWaybillMapper.selectByExample(dwe);
        DWaybill dw = list.size() > 0 ? list.get(0) : null;
        if (null != dw) {
            LOGGER.info("checkDwaybillIsCancel，获取取消运单信息：{}", JSONObject.toJSONString(dw));
            // 将运单取消状态回滚到初始化状态
            DWaybill newDw = new DWaybill();
            newDw.setId(dw.getId());
            newDw.setUserId(0L);
            newDw.setWaybillStatus(DWaybillStatusEnum.SAVE.getValue());
            this.dWaybillMapper.updateByPrimaryKeySelective(newDw);
            LOGGER.info("checkDwaybillIsCancel，修改运单状态：{}", JSONObject.toJSONString(newDw));
            // 加入队列
            TmsQueueOrderVo tqov = new TmsQueueOrderVo();
            tqov.setWaybillId(dw.getId().toString());
            tqov.setTmsSerialNo(dw.getOrderLineId().toString());
            tqov.setFrom(dw.getDepartureCity());
            tqov.setTo(dw.getDestCity());
            tqov.setUrgent(dw.getIsUrgent());
            this.tmsQueueService.appendOrder(tqov);
            LOGGER.info("checkDwaybillIsCancel，添加运单到队列：{}", JSONObject.toJSONString(tqov));
            // 添加日志
            this.dWaybillStatusHistoryService.add(dw.getId(), DWaybillStatusTypeEnum.PROCESS.getText(),
                    DWaybillStatusEnum.SAVE.getText(), DWaybillStatusEnum.getByValue(dw.getWaybillStatus()).getText(), 0L, "系统重置");
        }
    }

    @Override
    public Long add(TmsOrder tmsOrder) {
        if (null == tmsOrder) {
            LOGGER.error("add param tmsOrder must not null");
            throw new IllegalArgumentException("TMS订单不能为空");
        }

        tmsOrderMapper.insertSelective(tmsOrder);

        //保存订单状态变更
        TmsOrderStatusHistory history = new TmsOrderStatusHistory();
        history.setOrderId(tmsOrder.getId());
        history.setCurrentStatus(tmsOrder.getOpration());
        history.setUserId(0L);
        history.setUserName("系统导入");
        history.setReason("接口导入");
        tmsOrderStatusHistoryService.add(history);

        return tmsOrder.getId();
    }

    @Override
    public TmsOrder getTmsOrderByIlineid(String ilineid) {
        LOGGER.info("getTmsOrderByIlineid param : {}", ilineid);
        if (null == ilineid) {
            LOGGER.error("getTmsOrderByIlineid param ilineid must not be null");
            throw new IllegalArgumentException("订单流水号不能为空");
        }

        TmsOrderExample example = new TmsOrderExample();
        example.createCriteria().andIlineidEqualTo(ilineid);

        List<TmsOrder> list = tmsOrderMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void updateConfirmCost(Long orderId, String confirmCost, Date recoveryTime) {
        LOGGER.info("updateConfirmCost params : {}", orderId, confirmCost);
        if (null == orderId) {
            LOGGER.error("updateConfirmCost param orderId must not be null");
            throw new IllegalArgumentException("TMS订单主键不能为空");
        }
//        if(StringUtils.isBlank(confirmCost)){
//            LOGGER.error("updateConfirmCost param confirmCost must not be null");
//            throw new IllegalArgumentException("回单确认订单价格不能为空");
//        }

        TmsOrder order = new TmsOrder();
        order.setId(orderId);
        if (StringUtils.isNotBlank(confirmCost)) {
            order.setConfirmCost(confirmCost);
        }
        order.setDtreturn(recoveryTime);
        tmsOrderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public TmsOrder selectByPrimaryKey(Long id) {
        LOGGER.info("TmsOrderServiceImpl.selectByPrimaryKey param : {}", id);

        if ( null == id || 0 == id.intValue() ) {
            LOGGER.error("TmsOrderServiceImpl.selectByPrimaryKey param id must not be null");
            throw new IllegalArgumentException("主键不能为空");
        }

        return tmsOrderMapper.selectByPrimaryKey(id);
    }

}
